//
//  YCCameraAnimationManager.swift
//  YCCamera
//
//  Created by Billy on 2024/11/6.
//

import UIKit

class YCCameraAnimationManager {
    
    // MARK: - Shutter Animation (相机启动动画)
    
    /// 执行相机镜头打开动画
    static func performShutterOpenAnimation(
        topView: UIView,
        bottomView: UIView,
        containerBounds: CGRect,
        completion: (() -> Void)? = nil
    ) {
        // 防止重复执行动画
        if topView.layer.animationKeys()?.isEmpty == false {
            print("⚠️ 相机启动动画已在进行中，跳过")
            return
        }
        
        let shutterHeight = containerBounds.height / 2
        
        // 准备动画 - 确保初始状态是关闭的
        topView.isHidden = false
        bottomView.isHidden = false
        topView.frame = CGRect(x: 0, y: 0, width: containerBounds.width, height: shutterHeight)
        bottomView.frame = CGRect(x: 0, y: shutterHeight, width: containerBounds.width, height: shutterHeight)
        topView.transform = .identity
        bottomView.transform = .identity
        
        // 执行动画：向外展开
        UIView.animate(
            withDuration: YCCameraConstants.Animation.shutterOpenDuration,
            delay: 0,
            options: .curveEaseInOut
        ) {
            // 上半部分向上移动
            topView.transform = CGAffineTransform(translationX: 0, y: -shutterHeight)
            // 下半部分向下移动
            bottomView.transform = CGAffineTransform(translationX: 0, y: shutterHeight)
        } completion: { _ in
            // 动画完成后隐藏视图
            topView.isHidden = true
            bottomView.isHidden = true
            topView.transform = .identity
            bottomView.transform = .identity
            completion?()
        }
    }
    
    /// 执行相机镜头关闭动画
    static func performShutterCloseAnimation(
        topView: UIView,
        bottomView: UIView,
        containerBounds: CGRect,
        completion: (() -> Void)? = nil
    ) {
        let shutterHeight = containerBounds.height / 2
        
        // 准备动画 - 初始位置是分开的
        topView.isHidden = false
        bottomView.isHidden = false
        topView.transform = CGAffineTransform(translationX: 0, y: -shutterHeight)
        bottomView.transform = CGAffineTransform(translationX: 0, y: shutterHeight)
        
        // 执行动画：向中间合拢
        UIView.animate(
            withDuration: YCCameraConstants.Animation.shutterCloseDuration,
            delay: 0,
            options: .curveEaseInOut
        ) {
            topView.transform = .identity
            bottomView.transform = .identity
        } completion: { _ in
            completion?()
        }
    }
    
    // MARK: - Photo Flash Animation (拍照闪光动画)
    
    /// 执行拍照时的闪光效果
    static func performPhotoFlashAnimation(
        view: UIView,
        completion: (() -> Void)? = nil
    ) {
        // 快速显示黑色遮罩
        UIView.animate(
            withDuration: YCCameraConstants.Animation.photoFlashDuration,
            animations: {
                view.alpha = 1.0
            }
        ) { _ in
            // 快速淡出
            UIView.animate(
                withDuration: YCCameraConstants.Animation.photoFlashDuration,
                delay: YCCameraConstants.Animation.photoFlashDelay,
                options: .curveEaseOut
            ) {
                view.alpha = 0
            } completion: { _ in
                completion?()
            }
        }
    }
    
    // MARK: - Focus Animation (聚焦动画)
    
    /// 执行聚焦光标动画
    static func performFocusAnimation(
        view: UIView,
        at point: CGPoint,
        completion: (() -> Void)? = nil
    ) {
        view.center = point
        view.alpha = 1
        
        let scaleAnimation1 = CABasicAnimation(keyPath: "transform.scale")
        scaleAnimation1.fromValue = YCCameraConstants.Focus.animationScaleStart
        scaleAnimation1.toValue = YCCameraConstants.Focus.animationScaleMiddle
        scaleAnimation1.duration = YCCameraConstants.Focus.animationPhaseDuration
        
        let scaleAnimation2 = CABasicAnimation(keyPath: "transform.scale")
        scaleAnimation2.fromValue = YCCameraConstants.Focus.animationScaleMiddle - 0.05
        scaleAnimation2.toValue = YCCameraConstants.Focus.animationScaleEnd
        scaleAnimation2.duration = YCCameraConstants.Focus.animationPhaseDuration
        scaleAnimation2.beginTime = CACurrentMediaTime() + YCCameraConstants.Focus.animationPhaseDuration
        
        let fadeShowAnimation = CABasicAnimation(keyPath: "opacity")
        fadeShowAnimation.fromValue = 0
        fadeShowAnimation.toValue = 1
        fadeShowAnimation.duration = YCCameraConstants.Focus.animationPhaseDuration
        
        let fadeDismissAnimation = CABasicAnimation(keyPath: "opacity")
        fadeDismissAnimation.fromValue = 1
        fadeDismissAnimation.toValue = 0
        fadeDismissAnimation.duration = YCCameraConstants.Focus.animationPhaseDuration
        fadeDismissAnimation.beginTime = CACurrentMediaTime() + YCCameraConstants.Focus.animationFadeDelay
        
        let group = CAAnimationGroup()
        group.animations = [scaleAnimation1, scaleAnimation2, fadeShowAnimation, fadeDismissAnimation]
        group.duration = YCCameraConstants.Focus.focusDuration
        group.fillMode = .forwards
        group.isRemovedOnCompletion = false
        
        CATransaction.begin()
        CATransaction.setCompletionBlock {
            view.alpha = 0
            view.layer.removeAllAnimations()
            completion?()
        }
        view.layer.add(group, forKey: "focusAnimation")
        CATransaction.commit()
    }
    
    // MARK: - Filter Name Display (滤镜名称显示)
    
    /// 显示滤镜名称标签
    static func showFilterName(
        label: UILabel,
        text: String
    ) {
        label.text = text
        
        // 重置任何正在进行的动画
        label.layer.removeAllAnimations()
        label.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
        label.alpha = 0
        
        // 执行显示动画
        UIView.animate(
            withDuration: YCCameraConstants.Animation.filterNameFadeDuration,
            delay: 0,
            options: [.curveEaseOut]
        ) {
            label.transform = .identity
            label.alpha = 1
        } completion: { _ in
            // 延迟后淡出
            DispatchQueue.main.asyncAfter(deadline: .now() + YCCameraConstants.Animation.filterNameDisplayDuration) {
                UIView.animate(withDuration: YCCameraConstants.Animation.filterNameFadeDuration) {
                    label.alpha = 0
                }
            }
        }
    }
    
    // MARK: - Latest Photo Animation (最新照片动画)
    
    /// 执行最新照片缩略图动画
    static func performLatestPhotoAnimation(
        imageView: UIImageView,
        image: UIImage
    ) {
        imageView.alpha = 1.0
        imageView.image = image
        
        // 简化动画效果 - 快速缩放
        imageView.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
        UIView.animate(withDuration: 0.1) {
            imageView.transform = .identity
        }
    }
    
    // MARK: - Filter Change Animation (滤镜切换动画)
    
    enum FilterChangeDirection {
        case left
        case right
    }
    
    /// 执行滤镜切换动画效果
    static func performFilterChangeAnimation(
        in containerView: UIView,
        direction: FilterChangeDirection
    ) {
        // 创建一个临时视图来显示动画效果
        let animationView = UIView(frame: containerView.bounds)
        animationView.backgroundColor = UIColor.black.withAlphaComponent(0.2)
        containerView.addSubview(animationView)
        
        // 设置初始位置（从屏幕边缘开始）
        let screenWidth = containerView.bounds.width
        animationView.transform = CGAffineTransform(
            translationX: direction == .left ? screenWidth : -screenWidth,
            y: 0
        )
        
        // 执行动画
        UIView.animate(
            withDuration: 0.3,
            delay: 0,
            options: [.curveEaseOut]
        ) {
            animationView.transform = .identity
        } completion: { _ in
            UIView.animate(withDuration: 0.2) {
                animationView.alpha = 0
            } completion: { _ in
                animationView.removeFromSuperview()
            }
        }
    }
}

